package ms.jacrim;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import ms.jacrim.pddl.PddlSolution;
import ms.jacrim.pddl.SolutionEvaluatorManager;
import ms.jacrim.pddl.evaluator.LengthEvaluator;

public class GenerateSolution {

	String	command;
	int		expectedSolutions;
	boolean	plannerStopped	= false;
	Process	lpg;

	public void runPlanner() throws IOException, InterruptedException {

		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					String arg = String.format("%s -n %d ", command, expectedSolutions);
					ProcessBuilder b = new ProcessBuilder(Constants.CMD_PATH, "/C", arg);
					// lpg = b.start();
					// lpg.waitFor();

					b.redirectErrorStream(true);
					lpg = b.start();

					// process output
					InputStream is = lpg.getInputStream();
					InputStreamReader isr = new InputStreamReader(is);
					BufferedReader br = new BufferedReader(isr);
					String line;
					while ((line = br.readLine()) != null) {
						System.out.println(line);
					}
					System.out.println("Planner completed.");
					plannerStopped = true;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		t.start();
	}

	public void evaluatePlans() throws Exception {
		int current = 1;
		SolutionEvaluatorManager sem = new SolutionEvaluatorManager();
		sem.addEvaluator(new LengthEvaluator(1));
		do {
			Thread.sleep(1000);
			String filename = command + "_" + current + ".SOL";
			File f = new File(filename);
			if (f.exists()) {
				System.out.println("Solution found: #" + current);
				PddlSolution sol = new PddlSolution(null, filename);
				sem.evaluate(sol, true);
				current++;
			} else if (plannerStopped)
				break;
		} while (current > expectedSolutions);
	}

	/**
	 * @param args
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public static void main(String[] args) throws FileNotFoundException, IOException {
		if (args.length != 2) {
			System.out.println("Syntax: generateSolution <PDDL file> <expected_number_of_solutions>");
			System.exit(1);
		}

		Properties p = new Properties();
		p.load(new FileInputStream("conf/jacrim.conf"));
		
		String pddlFile = args[0];
		int sol = Integer.parseInt(args[1]);

		GenerateSolution ins = new GenerateSolution();

		System.out.println("Launching planner...");

		try {
			ins.runPlanner();
			ins.evaluatePlans();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
